require 'cgi'
require 'wpspider/common/http_request'
require 'wpspider/common/http_response'

module WPSpider
  module Common

    #
    # CGI class.
    #
    class CGI
      # Constructor is private.
      private_class_method :new

      #
      # Starts CGI.
      #
      def CGI::start()
        cgi = ::CGI.new()
        http_req = HttpRequest.new(cgi)
        http_res = HttpResponse.new(cgi)
        begin
          yield(http_req, http_res)
        rescue Exception
          http_res.set_content_type('text/plain')
          http_res.add_body($!.message + $/)
          http_res.add_body($!.backtrace.join($/))
        end
        cgi.out(http_res.get_headers()) do 
          http_res.get_body()
        end
      end
    end
  end
end
